import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:seedfour/app/views/module_case/case_detail/widget/approve_list.dart';
import 'package:seedfour/app/views/module_case/case_detail/widget/case_info.dart';
import 'package:seedfour/app/views/module_case/case_detail/widget/contract.dart';
import 'package:seedfour/app/views/module_case/case_detail/widget/income_order_list.dart';
import 'package:seedfour/app/views/module_case/case_detail/widget/paid_order_list.dart';

import '../../../constants.dart';
import '../../../theme.dart';
import 'logic.dart';

class CaseDetailPage extends StatelessWidget {
  CaseDetailPage({Key? key}) : super(key: key);

  final logic = Get.find<CaseDetailLogic>();
  final state = Get.find<CaseDetailLogic>().state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('案件详情'),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            size: 16.w,
          ),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: Obx(() {
        if (state.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        } else {
          return ListView(
            children: [
              SizedBox(height: kSpaceMedium),
              CaseInfoWidget(data: state),
              SizedBox(height: kSpaceMedium),
              ApproveListWidget(data: state),
              SizedBox(height: kSpaceMedium),
              ContractWidget(
                data: state,
                onApplyOfSeal: () => logic.toApplySeal(),
                onDownloadFile: (index) => logic.downloadFile(index),
                onDeleteFile: (index) => logic.deleteFile(index),
                onUploadContract: () => logic.uploadContract(),
              ),
              SizedBox(height: kSpaceMedium),
              IncomeOrderListWidget(
                data: state,
                onSelectOrder: () =>
                    logic.getCaseIncomeOrders(() => _showIncomeOrders()),
              ),
              SizedBox(height: kSpaceMedium),
              PaidOrderListWidget(
                data: state,
                onSelectOrder: () =>
                    logic.getCasePaidOrders(() => _showPaidOrders()),
              ),
              SizedBox(height: kSpaceMedium),
            ],
          );
        }
      }),
    );
  }

  // 付款订单关联窗口
  void _showPaidOrders() {
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: Get.context!,
      isDismissible: false,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(15.w)),
      ),
      builder: (context) {
        return Obx(
          () => SizedBox(
            width: double.infinity,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  color: Colors.white,
                  padding: EdgeInsets.symmetric(
                      horizontal: kSpaceMedium, vertical: kSpaceSmall),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '可关联订单',
                        style: TextStyle(
                          fontSize: kFontSizeLarge,
                          color: AppColor.colorFontBlack,
                          fontWeight: AppFont.fontMedium,
                        ),
                      ),
                      Container(
                        height: 40.w,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(50.w),
                          border: Border.all(
                            color: AppColor.colorBorderGrey,
                          ),
                        ),
                        child: TextButton(
                          onPressed: () => logic.showPaidDateTimePicker(),
                          child: Row(
                            children: [
                              Text(
                                '${DateFormat('yyyy.MM.dd').format(DateTime.fromMillisecondsSinceEpoch(state.paidOrderStartTime.value))}-${DateFormat('yyyy.MM.dd').format(DateTime.fromMillisecondsSinceEpoch(state.paidOrderEndTime.value))}',
                                style: TextStyle(
                                  fontSize: kFontSizeMini,
                                  color: AppColor.colorFontBlack,
                                ),
                              ),
                              SizedBox(width: kSpaceMini),
                              Icon(
                                Icons.keyboard_arrow_down,
                                size: 20.w,
                                color: AppColor.colorFontGrey,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                const Divider(),
                Expanded(
                  child: ListView.separated(
                    separatorBuilder: (context, index) =>
                        SizedBox(height: kSpaceMedium),
                    padding: EdgeInsets.all(kSpaceMedium),
                    itemCount: state.unselectPaidOrders.length,
                    itemBuilder: (context, index) {
                      return Obx(
                        () => Ink(
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(kRadiusMedium),
                            border: Border.all(
                              color: state.selectedPaidOrderIds.contains(
                                      state.unselectPaidOrders[index].id!)
                                  ? AppColor.colorFontBlue
                                  : AppColor.colorBorderGrey,
                            ),
                          ),
                          child: InkWell(
                            borderRadius: BorderRadius.circular(kRadiusMedium),
                            onTap: () => logic.onSelectedPaidOrder(
                                state.unselectPaidOrders[index].id!),
                            child: Padding(
                              padding: EdgeInsets.symmetric(
                                  horizontal: kSpaceMedium,
                                  vertical: kSpaceSmall),
                              child: Column(
                                children: [
                                  _buildItem(
                                    '订单号',
                                    state.unselectPaidOrders[index].id ?? '',
                                  ),
                                  SizedBox(height: kSpaceSmall),
                                  _buildItem(
                                      '创建时间',
                                      DateFormat('yyyy-MM-dd HH:mm').format(
                                          DateTime.fromMillisecondsSinceEpoch(
                                              state.unselectPaidOrders[index]
                                                      .createdAt ??
                                                  0))),
                                  SizedBox(height: kSpaceSmall),
                                  _buildItem(
                                      '对方户名',
                                      state.unselectPaidOrders[index]
                                              .agentUsername ??
                                          ''),
                                  SizedBox(height: kSpaceSmall),
                                  _buildItem(
                                      '收款金额',
                                      state.unselectPaidOrders[index]
                                              .orderAmountStr ??
                                          '¥0.00'),
                                  SizedBox(height: kSpaceSmall),
                                  _buildItem(
                                      '到账状态',
                                      (state.unselectPaidOrders[index]
                                                      .orderPayStatus ??
                                                  0) <
                                              7
                                          ? '未到账'
                                          : '已到账'),
                                  SizedBox(height: kSpaceSmall),
                                  _buildItem(
                                      '到账时间',
                                      state.unselectPaidOrders[index]
                                              .collectionDateStr ??
                                          ''),
                                  SizedBox(height: kSpaceSmall),
                                  _buildItem(
                                      '押金',
                                      state.unselectPaidOrders[index]
                                              .marginAmountStr ??
                                          '¥0.00'),
                                ],
                              ),
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
                const Divider(),
                Container(
                  color: Colors.white,
                  padding: EdgeInsets.symmetric(
                      horizontal: kSpaceMedium, vertical: kSpaceSmall),
                  child: Row(
                    children: [
                      Expanded(
                        flex: 4,
                        child: FilledButton(
                          onPressed: () => {
                            state.selectedPaidOrderIds.clear(),
                            Get.back(),
                          },
                          style: ButtonStyle(
                            backgroundColor:
                                WidgetStateProperty.all(AppColor.colorBtnGrey),
                            foregroundColor: WidgetStateProperty.all(
                                AppColor.colorFontBlack),
                            shape: WidgetStateProperty.all(
                              RoundedRectangleBorder(
                                borderRadius:
                                    BorderRadius.circular(kRadiusMedium),
                              ),
                            ),
                          ),
                          child: Padding(
                            padding:
                                EdgeInsets.symmetric(vertical: kSpaceSmall),
                            child: const Text('取消'),
                          ),
                        ),
                      ),
                      SizedBox(width: kSpaceMini),
                      Expanded(
                          flex: 6,
                          child: FilledButton(
                            onPressed: () => logic.addPaidOrders(),
                            child: Padding(
                              padding:
                                  EdgeInsets.symmetric(vertical: kSpaceSmall),
                              child: const Text('关联'),
                            ),
                          )),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  // 收款订单关联窗口
  void _showIncomeOrders() {
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: Get.context!,
      isDismissible: false,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(15.w)),
      ),
      builder: (context) {
        return Obx(
          () => SizedBox(
            width: double.infinity,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  color: Colors.white,
                  padding: EdgeInsets.symmetric(
                      horizontal: kSpaceMedium, vertical: kSpaceSmall),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '可关联订单',
                        style: TextStyle(
                          fontSize: kFontSizeLarge,
                          color: AppColor.colorFontBlack,
                          fontWeight: AppFont.fontMedium,
                        ),
                      ),
                      Container(
                        height: 40.w,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(50.w),
                          border: Border.all(
                            color: AppColor.colorBorderGrey,
                          ),
                        ),
                        child: TextButton(
                          onPressed: () => logic.showIncomeDateTimePicker(),
                          child: Row(
                            children: [
                              Text(
                                '${DateFormat('yyyy.MM.dd').format(DateTime.fromMillisecondsSinceEpoch(state.incomeOrderStartTime.value))}-${DateFormat('yyyy.MM.dd').format(DateTime.fromMillisecondsSinceEpoch(state.incomeOrderEndTime.value))}',
                                style: TextStyle(
                                  fontSize: kFontSizeMini,
                                  color: AppColor.colorFontBlack,
                                ),
                              ),
                              SizedBox(width: kSpaceMini),
                              Icon(
                                Icons.keyboard_arrow_down,
                                size: 20.w,
                                color: AppColor.colorFontGrey,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                const Divider(),
                Expanded(
                  child: ListView.separated(
                    separatorBuilder: (context, index) =>
                        SizedBox(height: kSpaceMedium),
                    padding: EdgeInsets.all(kSpaceMedium),
                    itemCount: state.unselectIncomeOrders.length,
                    itemBuilder: (context, index) {
                      return Obx(
                        () => Ink(
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(kRadiusMedium),
                            border: Border.all(
                              color: state.selectedIncomeOrderIds.contains(
                                      state.unselectIncomeOrders[index].id!)
                                  ? AppColor.colorFontBlue
                                  : AppColor.colorBorderGrey,
                            ),
                          ),
                          child: InkWell(
                            borderRadius: BorderRadius.circular(kRadiusMedium),
                            onTap: () => logic.onSelectedIncomeOrder(
                                state.unselectIncomeOrders[index].id!),
                            child: Padding(
                              padding: EdgeInsets.symmetric(
                                  horizontal: kSpaceMedium,
                                  vertical: kSpaceSmall),
                              child: Column(
                                children: [
                                  _buildItem(
                                    '订单号',
                                    state.unselectIncomeOrders[index].id ?? '',
                                  ),
                                  SizedBox(height: kSpaceSmall),
                                  _buildItem(
                                      '创建时间',
                                      DateFormat('yyyy-MM-dd HH:mm').format(
                                          DateTime.fromMillisecondsSinceEpoch(
                                              state.unselectIncomeOrders[index]
                                                      .createdAt ??
                                                  0))),
                                  SizedBox(height: kSpaceSmall),
                                  _buildItem(
                                      '对方户名',
                                      state.unselectIncomeOrders[index].title ??
                                          ''),
                                  SizedBox(height: kSpaceSmall),
                                  _buildItem(
                                      '收款金额',
                                      state.unselectIncomeOrders[index]
                                              .orderAmountStr ??
                                          '¥0.00'),
                                  SizedBox(height: kSpaceSmall),
                                  _buildItem(
                                      '到账状态',
                                      (state.unselectIncomeOrders[index]
                                                      .orderChargeStatus ??
                                                  0) <
                                              7
                                          ? '未到账'
                                          : '已到账'),
                                  SizedBox(height: kSpaceSmall),
                                  _buildItem(
                                      '到账时间',
                                      state.unselectIncomeOrders[index]
                                              .collectionDateStr ??
                                          ''),
                                  SizedBox(height: kSpaceSmall),
                                  _buildItem(
                                      '押金',
                                      state.unselectIncomeOrders[index]
                                              .marginAmountStr ??
                                          '¥0.00'),
                                ],
                              ),
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
                const Divider(),
                Container(
                  color: Colors.white,
                  padding: EdgeInsets.symmetric(
                      horizontal: kSpaceMedium, vertical: kSpaceSmall),
                  child: Row(
                    children: [
                      Expanded(
                        flex: 4,
                        child: FilledButton(
                          onPressed: () => {
                            state.selectedIncomeOrderIds.clear(),
                            Get.back(),
                          },
                          style: ButtonStyle(
                            backgroundColor:
                                WidgetStateProperty.all(AppColor.colorBtnGrey),
                            foregroundColor: WidgetStateProperty.all(
                                AppColor.colorFontBlack),
                            shape: WidgetStateProperty.all(
                              RoundedRectangleBorder(
                                borderRadius:
                                    BorderRadius.circular(kRadiusMedium),
                              ),
                            ),
                          ),
                          child: Padding(
                            padding:
                                EdgeInsets.symmetric(vertical: kSpaceSmall),
                            child: const Text('取消'),
                          ),
                        ),
                      ),
                      SizedBox(width: kSpaceMini),
                      Expanded(
                          flex: 6,
                          child: FilledButton(
                            onPressed: () => logic.addIncomeOrders(),
                            child: Padding(
                              padding:
                                  EdgeInsets.symmetric(vertical: kSpaceSmall),
                              child: const Text('关联'),
                            ),
                          )),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildItem(String title, String value) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        _buildItemText(title, TextAlign.left),
        SizedBox(width: kSpaceLarge),
        Expanded(child: _buildItemText(value, TextAlign.right)),
      ],
    );
  }

  Widget _buildItemText(String text, TextAlign align) {
    return Text(
      text,
      textAlign: align,
      style: TextStyle(
        fontSize: kFontSizeSmall,
        color: AppColor.colorFontBlack,
      ),
    );
  }
}
